package com.tutu.user.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tutu.common.GlobalConstants;
import com.tutu.common.util.JsonReturnObject;
import com.tutu.common.util.LogAction;
import com.tutu.common.util.SysAuditModelType;
import com.tutu.user.entity.SysUser;

@Controller
@LogAction(ownermodel=SysAuditModelType.LOGIN_MANAGEMENT)
public class LoginAction {
	
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	@RequestMapping("/login")
	public String login(HttpSession session){
		JsonReturnObject<String> jsonReturnObject = new JsonReturnObject<String>(false, "用户登录信息输入有误!");
		try {
			Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
			SysUser sysUser = null;
			boolean isPrincipal = false;
			if(null!=authentication){
				Object object = authentication.getPrincipal();
				if(object instanceof SysUser){
					sysUser = (SysUser) object;
					isPrincipal = true;
				}
			}
			if(!isPrincipal){
				Object objexception = session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
				
				String rspMsg = "输入用户信息";
				if(objexception instanceof UsernameNotFoundException){
					UsernameNotFoundException usernameNotFoundException = (UsernameNotFoundException) objexception;
					usernameNotFoundException.getMessage();
					rspMsg = "用户登录信息输入有误!";
				}else if(objexception instanceof AuthenticationServiceException){
					AuthenticationServiceException authenticationServiceException = (AuthenticationServiceException) objexception;
					if(authenticationServiceException.getCause() instanceof NullPointerException){
						rspMsg = "系统中无此用户";
					}
				}else if(objexception instanceof LockedException){
					LockedException lockedException = (LockedException) objexception;
					rspMsg = "用户已锁定";
				}else if(objexception instanceof BadCredentialsException){
					BadCredentialsException badCredentialsException = (BadCredentialsException) objexception;
//					Authentication authentication = badCredentialsException.getAuthentication();
//					if(authentication.getDetails() instanceof WebAuthenticationDetails){
//						WebAuthenticationDetails webAuthenticationDetails = (WebAuthenticationDetails) authentication.getDetails();
//						webAuthenticationDetails.getRemoteAddress();
//					}
//					this.userService.lockUser(String.valueOf(authentication.getPrincipal()));
					
					rspMsg = "用户密码有误,或状态无效";
				}
				jsonReturnObject.setErrorMsg(rspMsg);
    		}else{
    			//取得用户的所有权限菜单 从数据库
    			if(CollectionUtils.isEmpty(sysUser.getAuthorities())) {
    				GlobalConstants.removeAllAttributes(session);
    				String errorMsg = "无使用本系统的权限!";
    				jsonReturnObject.setErrorMsg(errorMsg);
    			} else {
    				session.setAttribute(session.getId()+GlobalConstants.SESSION_USER_INFO, sysUser);
    			}
    			jsonReturnObject.setIsSuccess(true);
    		}
        } catch (Exception ex) {
            logger.error("登录失败", ex);
            GlobalConstants.removeAllAttributes(session);
            String errorMsg = "系统异常!请联系管理员!";
    		jsonReturnObject.setErrorMsg(errorMsg);
        }
		GlobalConstants.setSessionMessage(session, jsonReturnObject);
//		model.addAttribute("jsonReturnObject", jsonReturnObject);
		return "login";
	}
	
	@RequestMapping("/index")
	public String index(HttpServletRequest request, HttpServletResponse response) throws IOException{
		return "redirect:/msg/queryMyMsg.do";
	}
	
}
